<!-- 订单详情 -->
<template>
  <div
    v-loading="listLoading"
    class="dashboard-container edit-order"
    :class="{ 'loading-box': listLoading }"
    element-loading-text="加载中"
  >
    <div style="background-color:#fff;margin: 20px;padding: 30px;">
      <el-row style="margin-left: 30px;font-size: 16px;">
        <el-col :span="6">订单编号：{{ List.id }}</el-col>
        <el-col :span="6">运单编号：{{ List.memberId }}</el-col>
        <el-col :span="6">下单时间：{{ List.createTime }}</el-col>
        <el-col :span="6">订单状态：{{ statusL }}</el-col>
        <el-col
          :span="8"
          style="margin-top: 40px;"
        >预计到达日期：{{ List.estimatedArrivalTime }}</el-col>
      </el-row>
    </div>
    <div style="background-color:#fff;margin: 20px;">
      <span style="background-color:#f8faff;width: 100%;height: 50px;display:block;line-height: 50px;padding-left: 60px;"><strong>基本信息</strong></span>
      <div class="info">
        <p> <i
          class="el-icon-upload2"
          style="color:#99cbfd"
        ></i>发货方</p>
        <div style="">
          <p style="width: 800px;display: flex;justify-content:space-around;margin-left: -90px;"><span>发货方姓名：{{ List.senderName }}</span>
            <span>发货方电话：{{ List.senderPhone }}</span></p>
          <p style="width: 800px;display: flex;justify-content:space-around;margin-left: -90px;"><span>发货方地址：{{ List.senderProvince.name }}{{ List.senderCity.name }}{{ List.senderCounty.name }}</span><span>详情地址：{{ List.senderAddress }}</span></p>
        </div>
      </div>
      <div class="infoA">
        <p> <i
          class="el-icon-circle-plus"
          style="color:#99cbfd"
        ></i>收货方</p>
        <div style="">
          <p style="width: 800px;display: flex;justify-content:space-around;margin-left: -90px;"><span>收货方姓名：{{ List.receiverName }}</span>
            <span>收货方电话：{{ List.receiverPhone }}</span></p>
          <p style="width: 800px;display: flex;justify-content:space-around;margin-left: -90px;"><span>收货方地址：{{ List.receiverProvince.name }}{{ List.receiverCity.name }}{{ List.receiverCounty.name }}</span><span>详情地址：{{ List.receiverAddress }}</span></p>
        </div>
      </div>
      <div
        class="infoB"
      >
        <p> <i
          class="el-icon-question"
          style="color:#ffca28"
        ></i>距离: {{ List.distance }}km</p>
        <div style="">
          <p style="width: 800px;display: flex;justify-content:space-around;margin-left: -90px;"><span>备注：{{ List.mark===null?'暂无':List.mark }}</span><span>  </span>
          </p>
        </div>
      </div>
    </div>

    <!-- 订单跟踪 -->
    <div style="background-color:#fff;margin: 20px;">
      <span style="background-color:#f8faff;width: 100%;height: 50px;display:block;line-height: 50px;padding-left: 60px;"><strong>订单跟踪</strong></span>
      <div style="width: 100%;height: 600px;background-color:#fff">
        <!-- <div style="margin-left: 20px;display: flex;align-items: center;margin-top: 20px;margin-bottom: 20px;">
          <label>地区关键词：</label>
          <el-input
            v-model="keyword"
            placeholder="请输入地区关键词"
            style="width: 80%;"
            @input="handleInputfun"
          />
        </div> -->
        <baidu-map
          ref="myMap"
          class="map"
          :center="center"
          :zoom="zoom"
          :scroll-wheel-zoom="true"
          :map-click="false"
          @mousemove="syncPolyline"
          @click="paintPolyline"
          @rightclick="newPolyline"
          @ready="ready"
        >
          <bm-local-search
            :keyword="keyword"
            :auto-viewport="true"
            :panel="false"
          ></bm-local-search>
          <bm-control
            v-show="showSave"
            style="background: #fff; width: 100%"
          >
            <el-button
              type="primary"
              class="new-btn"
              @click="toggle('polyline')"
            >{{ polyline.editing ? '完成绘制' : '开始绘制' }}</el-button>
            <el-button
              v-show="polyline.editing !== false"
              style="
                  color: #818693;
                  border: 1px solid #d8dde3;
                  padding: 10px 20px;
                  margin-left: 12px;
                "
              class="dele"
              @click="clear()"
            >删除围栏</el-button>
            <P
              style="
                  font-size: 12px;
                  color: rgba(198, 126, 18, 1);
                  width: 100%;
                  background: rgba(255, 245, 231, 1);
                  width: 100%;
                  height: 30px;
                  line-height: 30px;
                  text-align: left;
                  padding-left: 10px;
                "
            ><img
              src="@/assets/warn.png"
              alt=""
              style="
                    width: 14px;
                    vertical-align: middle;
                    margin-bottom: 2px;
                    margin-right: 6px;
                  "
            />点击或拖动鼠标绘制作业范围，右击鼠标结束图形绘制，图形不可有交叉点。完成绘制后，点击提交按钮保存。每个机构仅可支持绘制一个作业范围</P>
          </bm-control>
          <bm-polygon
            v-for="(path, index) of polyline.paths"
            :key="index"
            :path="path"
            stroke-color="#e85552"
            fill-color="rgba(232,85,82,0.30)"
            :fill-opacity="0.9"
            :stroke-opacity="0.5"
            :stroke-weight="1"
            :editing="polyline.editing"
            stroke-style="dashed"
            @lineupdate="updatePolygonPath"
          />
        </baidu-map>
      </div>
    </div>

    <!-- 取件信息 -->
    <div style="background-color:#fff;margin: 20px;">
      <span style="background-color:#f8faff;width: 100%;height: 50px;display:block;line-height: 50px;padding-left: 60px;"><strong>取件信息</strong></span>
      <el-row style="margin-left: 100px;margin-top: 50px;">
        <el-col :span="6"><span>所在网点：{{ List.taskPickup.agency.name }}</span></el-col>
        <el-col :span="6"><span>取件类型: {{ List.pickupType===1?'网点自寄':'上门取件' }}</span></el-col>
        <el-col :span="6"><span>作业状态：{{ pS }}</span></el-col>
        <el-col :span="6"><span>取件快递员: {{ List.taskPickup.courier.creator }}</span></el-col>
      </el-row>
      <el-row style="margin-left: 100px;margin-top: 40px;margin-bottom: 50px;padding-bottom: 50px;">
        <el-col :span="6"><span>快递员电话: {{ List.taskPickup.courier.mobile }}</span></el-col>
        <el-col :span="6"><span>预计取件时间: {{ List.taskPickup.estimatedStartTime }}</span></el-col>
        <el-col :span="6"><span>取件完成时间: {{ List.taskPickup.estimatedEndTime }}</span></el-col>
      </el-row>

    </div>
    <!-- 费用信息 -->
    <div style="background-color:#fff;margin: 20px;">
      <span style="background-color:#f8faff;width: 100%;height: 50px;display:block;line-height: 50px;padding-left: 60px;"><strong>费用信息</strong></span>
      <el-row style="margin-left: 100px;margin-top: 50px;padding-bottom: 50px;">
        <el-col :span="6"><span>运费:<span style="color:#ffd700;font-weight:700;margin-left: 10px;margin-right: 10px;">{{ List.amount }}</span>元
        </span></el-col>
        <el-col :span="6"><span>支付方式: {{ List.paymentMethod===1?'预结':'到付' }}</span></el-col>
        <el-col :span="6"><span>付款状态：{{ List.paymentStatus===1?'未付':'已付' }}</span></el-col>
      </el-row>
    </div>
    <!-- 货品信息 -->
    <div style="background-color:#fff;margin: 20px;">
      <span style="background-color:#f8faff;width: 100%;height: 50px;display:block;line-height: 50px;padding-left: 60px;"><strong>货品信息</strong></span>
      <div style="padding: 20px;">
        <el-table
          :data="tableList"
          style="width: 100%;margin-bottom: 40px;"
          :show-summary="true"
          :model="row"
        >
          <el-table-column
            type="index"
            label="序号"
            width="80"
          >
          </el-table-column>

          <el-table-column
            label="货物名称"
            width="300px"
          >
            <template #default="{row}">
              {{ flag?row.name:'' }}
              <el-input
                v-show="flag===false"
                v-model="row.name"
                placeholder="请输入内容"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            width="300px"
            prop="goodsType.name"
            label="货物类型"
          >
            <template #default="{row}">
              {{ flag?row.goodsType.name:'' }}
              <el-input
                v-show="flag===false"
                v-model="row.goodsType.name "
                placeholder="请输入内容"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            width="300px"
            prop="totalWeight"
            label="重量(千克)"
          >
            <template #default="{row}">
              {{ flag?row.totalWeight:'' }}
              <el-input
                v-show="flag===false"
                v-model="row.totalWeight"
                placeholder="请输入内容"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            width="300px"
            prop="totalVolume"
            label="体积(立方)"
          >
            <template #default="{row}">
              {{ flag?row.totalVolume:'' }}
              <el-input
                v-show="flag===false"
                v-model="row.totalVolume "
                placeholder="请输入内容"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            label="操作"
            align="center"
          >
            <template #default="obj">
              <div v-show="flag===true">
                <el-link
                  type="primary"
                  :underline="false"
                  style="margin-right: 10px;"
                  @click="edit"
                >编辑</el-link> |  <el-link
                  type="danger"
                  :underline="false"
                  style="margin-left: 10px;"
                  @click="del(obj.row.id)"
                >删除</el-link>
              </div>

              <div v-show="flag===false">
                <el-link
                  type="primary"
                  :underline="false"
                  style="margin-right: 10px;"
                  @click="save"
                >保存</el-link> |  <el-link
                  type="danger"
                  :underline="false"
                  style="margin-left: 10px;"
                  @click="flag=!flag"
                >取消</el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>

      </div>
    </div>
  </div>
</template>
<script>
import { getOrderEdit, getGoodsType, postGoodsType, delGoodsType, getOrdercargo } from '@/api/orderManage.js'
import OrderStatus from '@/api/orderstatus.json'
import { courierAdd } from '@/api/branch'
export default {
  data() {
    return {
      keyword: '',
      showSave: false,
      loadingMap: false, // 地图加载loading
      center: {
        lng: 116.404,
        lat: 39.915
      },
      isOperation: false, // 解决已经作业范围时，编辑时会默认开启编辑状态
      zoom: 13, // 地图缩放级别
      polyline: {
        editing: false,
        paths: []
      }, // 作业范围,绘制的多边形

      listLoading: true,
      List: [],
      statusL: '',
      PStatus: [
        { id: 1, name: '新任务' },
        { id: 2, name: '已完成' },
        { id: 3, name: '已取消' }
      ],
      table: {
        cargoBarcode: null,
        goodsTypeId: '',
        name: '',
        orderId: '',
        quantity: 1,
        remark: null,
        totalVolume: '',
        totalWeight: ''
      },
      tableList: [],

      // row: {
      //   name: '',
      //   goodsType: { name: '' },
      //   totalWeight: '',
      //   totalVolume: ''
      // },
      pS: '',
      // orderCargoDTOSListb: [],
      flag: true,
      idGoods: ''
    }
  },
  created() {
    this.getList()
    this.getCargo()
  },
  methods: {
    // 组件注入map实例
    ready({ BMap, map }) {
      this.map = map
      this.BMap = BMap
    },
    async getCargo() {
      const res = await getOrdercargo(this.$route.query.id)
      this.tableList = res.data
    },
    async getList() {
      this.listLoading = true
      const { data } = await getOrderEdit(this.$route.query.id)
      this.listLoading = false
      this.List = data
      const index = OrderStatus.findIndex(item => item.id === data.status)
      this.statusL = OrderStatus[index].name
      const PIndex = this.PStatus.findIndex(item => item.id === data.taskPickup.status)
      this.pS = this.PStatus[PIndex].name
      console.log('代码', data)
      console.log(this.List.mark)
      this.center.lng = data.receiverCity.lng
      this.center.lat = data.receiverCity.lat
    },
    // 点击编辑
    async edit() {
      this.flag = !this.flag
      if (this.flag === false) {
        const res = await getGoodsType()
        const index = res.data.findIndex(item => item.name === this.orderCargoDTOSList[0].goodsType.name)
        this.idGoods = res.data[index].id
      }
    },
    // 点击保存
    async save() {
      this.table.goodsTypeId = this.List.memberId
      // this.table.name = this.List.orderCargoDTOS[0].name
      // this.table.orderId = this.$route.query.id
      // this.table.totalVolume = this.List.orderCargoDTOS[0].totalVolume
      // this.table.totalWeight = this.List.orderCargoDTOS[0].totalWeight
      const ids = this.$route.query.id
      console.log(this.table)

      await postGoodsType(ids, this.table)
      this.$message.success('编辑成功')
      await this.getList()
      this.flag = !this.flag
    },
    // 删除
    del(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delGoodsType(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        await this.getCargo()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 鼠标移动时
    syncPolyline(e) {
      if (!this.polyline.editing || !this.isOperation) {
        return
      }
      const { paths } = this.polyline
      if (!paths.length) {
        return
      }
      const path = paths[paths.length - 1]
      if (!path.length) {
        return
      }
      if (path.length === 1) {
        path.push(e.point)
      }
      this.$set(path, path.length - 1, e.point)
    },
    // 鼠标右键多边形绘制完成
    newPolyline(e) {
      if (!this.polyline.editing) {
        return
      }
      const { paths } = this.polyline
      if (!paths.length) {
        paths.push([])
      }
      const path = paths[paths.length - 1]
      path.pop()
      if (path.length) {
        paths.push([])
      }
    },
    // 鼠标左键点击时往路径里push一个点
    paintPolyline(e) {
      // 解决默认有电子围栏时，在绘制过程中有某些点可能会清空之前画的并且回到原点的问题
      if (!this.polyline.editing || this.isFirstEdit) {
        return
      }
      this.isOperation = true
      const { paths } = this.polyline
      !paths.length && paths.push([])
      paths[paths.length - 1].push(e.point)
    },

    // 在原有多边形的基础上继续绘制触发
    updatePolygonPath(e) {
      this.polygonPath = e.target.getPath()
    },

    // 到达地区关键词搜索
    handleInputfun() {
      // 重置中心点和缩放等级为了在编辑时可以重新回到绘制区域
      this.$set(this.center, 'lng', 0)
      this.$set(this.center, 'lat', 0)
      this.zoom = 0
    },
    // 编辑机构作业范围
    async editData() {
      this.showSave = true
      this.showEdit = false
      // 编辑的时候回到绘制的区域中心点
      // 根据坐标点自动调整地图的中心点和地图缩放等级
      const viewPointInfo = this.map && this.map.getViewport(this.polyline.paths[0])
      this.$set(this.center, 'lng', viewPointInfo.center.lng)
      this.$set(this.center, 'lat', viewPointInfo.center.lat)
      this.zoom = this.isHaveAgencyArange ? viewPointInfo.zoom : 11
    },
    // 保存机构作业范围
    async createData() {
      this.polyline.editing = false
      this.isOperation = false
      if (this.polyline.paths.length === 0) {
        return this.$message.error('请绘制作业机构范围')
      }
      // 用于解决绘画电子围栏时，取消默认选中点的绘画开启新的绘画时，无法提交的问题
      const arr = []
      this.polyline.paths.forEach((item) => {
        arr.push(item.length)
      })
      const max = Math.max(...arr)
      const indexOfMax = arr.indexOf(max)
      // point是经纬度数组，即坐标点
      const point = (
        !this.isFirstEdit ? this.polyline.paths[indexOfMax] : this.polygonPath
      ).map((item) => {
        return { latitude: item.lat, longitude: item.lng }
      })
      point.push(point[0]) // 需要闭环所以前端这边手动在数组末尾加上第一个坐标点
      const data = {
        polygon: point,
        type: 1,
        bid: this.agencyId
      }
      // 发送请求，调用接口，保存数据
      await courierAdd(data)
        .then((res) => {
          if (res.code === 200) {
            this.showSave = false
            this.showEdit = true
            this.$emit('newDataes', this.newDataes)
            this.$message.success('电子围栏保存成功')
            this.$set(this.polyline, 'editing', false)
          } else {
            this.$message.error(res.msg || '电子围栏保存失败')
          }
        })
        .catch(() => {
          this.$message.error('电子围栏保存失败')
        })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
@import './index.scss';
.info{
   width: 100%;
   background-color:#fff;
   padding-right: 700px;
   padding-left: 60px;
   padding-top: 40px;
}
.infoA{
   width: 100%;
   background-color:#fff;
   padding-right: 700px;
   padding-left: 60px;
   padding-top: 10px;
}
.infoB{
   width: 100%;
   background-color:#fff;
   padding-right: 700px;
   padding-left: 60px;
   padding-top: 10px;
   padding-bottom: 50px;
}
// ::v-deep

</style>

